// @preview-file on clear nolog
import { React, toNode, useRef } from 'DoraX';
import { Content, Vec2, } from 'Dora';
import { Savefile } from 'Script/config';

export const actName = ["新存档", "第一幕", "银杏小镇","终幕"];

function savefileToText(savefile: Savefile): string {
  const lines: string[] = [];
  lines.push(`act:${savefile.act}`);
  lines.push(`playTime:${savefile.playTime}`);
  lines.push(`player_pos:${savefile.player_pos.x},${savefile.player_pos.y}`);
  const taskParts: string[] = [];
  for (const task of savefile.tasks) {
    let escapedTask = task;
    let index = -1;
    while ((index = escapedTask.indexOf('"', index + 1)) !== -1) {
      escapedTask = escapedTask.substring(0, index) + '\\"' + escapedTask.substring(index + 1);
      index++;
    }
    if (escapedTask.includes(',') || escapedTask.includes('"')) {
      taskParts.push(`"${escapedTask}"`);
    } else {
      taskParts.push(escapedTask);
    }
  }
  lines.push(`tasks:${taskParts.join(',')}`);
  const packageParts: string[] = [];
  for (const item of savefile.package) {
    packageParts.push(item.toString());
  }
  lines.push(`package:${packageParts.join(',')}`);
  const progressParts: string[] = [];
  for (const prog of savefile.progress) {
    progressParts.push(prog.toString());
  }
  lines.push(`progress:${progressParts.join(',')}`);
  return lines.join('\n');
}

function textToSavefile(text: string): Savefile {
  const lines = text.split('\n');
  const result: Partial<Savefile> = {};
  for (const line of lines) {
    const colonIndex = line.indexOf(':');
    if (colonIndex === -1) continue;
    const key = line.substring(0, colonIndex);
    const value = line.substring(colonIndex + 1);
    switch (key) {
      case 'act':
      case 'playTime':
        result[key] = parseFloat(value);
        break;
      case 'player_pos':
        const coords = value.split(',');
        if (coords.length >= 2) {
          const x = parseFloat(coords[0]);
          const y = parseFloat(coords[1]);
          if (!isNaN(x) && !isNaN(y)) {
            result[key] = Vec2(x, y);
          }
        }
        break;
      case 'tasks':
        const tasks: string[] = [];
        let current = '';
        let inQuotes = false;
        let escapeNext = false;
        for (let i = 0; i < value.length; i++) {
          const char = value[i];
          if (escapeNext) {
            current += char;
            escapeNext = false;
          } else if (char === '\\') {
            escapeNext = true;
          } else if (char === '"') {
            inQuotes = !inQuotes;
          } else if (char === ',' && !inQuotes) {
            tasks.push(current);
            current = '';
          } else {
            current += char;
          }
        }
				if(current!=''){
        	tasks.push(current);
				}
        result[key] = tasks;
        break;
      case 'package':
      case 'progress':
        const numStrs = value.split(',');
        const nums: number[] = [];
        for (const numStr of numStrs) {
          const num = parseFloat(numStr);
          if (!isNaN(num)) {
            nums.push(num);
          }
        }
        result[key] = nums;
        break;
    }
  }
  const finalResult: Savefile = {
    act: result.act || 1,
    playTime: result.playTime || 0,
    player_pos: result.player_pos || Vec2(0, 0),
    tasks: result.tasks || [],
    package: result.package || [],
    progress: result.progress || [],
  };
  return finalResult;
}

// 存档管理类
export class SaveManager {
  private saveDir: string = "Save";

  constructor() {
    this.ensureSaveDir();
  }

  // 确保存档目录存在
  private ensureSaveDir() {
    if (!Content.isdir(this.saveDir)) {
      Content.mkdir(this.saveDir);
    }
  }

  // 获取存档文件路径
  private getSavePath(slot: number): string {
    return `${this.saveDir}/save${slot}`;
  }
  createDefaultSave(): Savefile {
    return {
      act: 0,
      playTime: 0,
      player_pos: Vec2(0, 0),
      tasks: [],
      package: [],
      progress: [],
    };
  }

  getAllSaves(maxSlots: number): Savefile[] {
    const saves: Savefile[] = [];
    this.ensureSaveDir();

    for (let slot = 0; slot < maxSlots; slot++) {
      const savePath = this.getSavePath(slot);

      // 检查文件是否存在
      if (!Content.exist(savePath)) {
        // 文件不存在，创建默认存档
        const defaultSave = this.createDefaultSave();
        const content = savefileToText(defaultSave);
        Content.save(savePath, content);
        saves.push(defaultSave);
      } else {
        // 文件存在，读取并解析
        try {
          const content = Content.load(savePath);
          const save = textToSavefile(content);
          saves.push(save);
        } catch (error) {
          // 读取失败，创建默认存档
          print(`读取存档 ${slot} 失败:`, error);
          const defaultSave = this.createDefaultSave();
          saves.push(defaultSave);

          // 尝试覆盖损坏的存档
          try {
            const content = savefileToText(defaultSave);
            Content.save(savePath, content);
          } catch (saveError) {
            print(`修复存档 ${slot} 失败:`, saveError);
          }
        }
      }
    }
    return saves;
  }


  saveGame(slot: number, savefile: Savefile): boolean {
    const content = savefileToText(savefile);
    const savePath = this.getSavePath(slot);
    return Content.save(savePath, content);
  }

  deleteSave(slot: number): boolean {
		const content = savefileToText(this.createDefaultSave());
    const savePath = this.getSavePath(slot);
    return Content.save(savePath,content);
    // return Content.remove(this.getSavePath(slot));
  }
}
